﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
using System.IO;

public partial class mobile_discount : System.Web.UI.Page
{
    string dis_id;
    string ind_id; 
    string d_title="";
        string d_rate="";
        DateTime d_start=new DateTime();
        DateTime d_end=new DateTime();
        int d_vip=0;
        string d_rules="";
        string d_image="";
        string d_type="";
        int cred;
        double disc;
        private static string key = "TEST2013";
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
        public static string DESencode(string str)
        {
            try
            {
                byte[] rgbkey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] rgbIV = rgbkey;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mstream = new MemoryStream();
                CryptoStream cstream = new CryptoStream(mstream, dCSP.CreateEncryptor(rgbkey, rgbIV), CryptoStreamMode.Write);
                cstream.Write(inputByteArray, 0, inputByteArray.Length);
                cstream.FlushFinalBlock();
                cstream.Close();
                return Convert.ToBase64String(mstream.ToArray());
            }
            catch
            {
                return str;
            }
        }

    protected void Page_Load(object sender, EventArgs e)
    {
        dis_id = this.Request.Params["did"];
        ind_id=this.Request.Params["indid"];
       
        SqlConnection sc1 = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
        sc1.Open();
        SqlCommand get_discount = new SqlCommand();
        get_discount.Connection = sc1;
        get_discount.CommandText = "select DISCOUNT_TITLE,DIS_RATE,DISCOUNT_START,DISCOUNT_END,VIP,RULES,DISCOUNT_IMAGE,DISCOUNT_TYPE from INFO_DISCOUNT where DISCOUNT_ID=@id";
        get_discount.Parameters.AddWithValue("@id",dis_id);
        SqlDataReader r=get_discount.ExecuteReader();
        while (r.Read())
        {
            d_title = r.GetString(r.GetOrdinal("DISCOUNT_TITLE"));
            d_rate= r.GetString(r.GetOrdinal("DIS_RATE"));
            d_start= r.GetDateTime(r.GetOrdinal("DISCOUNT_START"));
            d_end= r.GetDateTime(r.GetOrdinal("DISCOUNT_END"));
            d_vip= r.GetInt32(r.GetOrdinal("VIP"));
            d_rules= r.GetString(r.GetOrdinal("RULES"));
            d_image= r.GetString(r.GetOrdinal("DISCOUNT_IMAGE"));
            d_type=r.GetString(r.GetOrdinal("DISCOUNT_TYPE"));

        }
        r.Close();
        SqlCommand get_cred = new SqlCommand();
        get_cred.Connection = sc1;
        get_cred.CommandText = "select IND_CREDITS from INFO_IND where IND_ID=@id";
        get_cred.Parameters.AddWithValue("@id", ind_id);
        int crr = Convert.ToInt32(get_cred.ExecuteScalar());
       
        int rate_stop=d_rate.IndexOf('/');
        cred = Convert.ToInt32(d_rate.Substring(0,rate_stop));
        disc = Convert.ToDouble(d_rate.Remove(0,rate_stop+1));
        label1.Text = d_title;
        label2.Text = "您目前拥有"+crr+"积分。<br />需要花费"+cred+"积分，可以获得";
        if (d_type.Equals("CREDIT_EXCHANGE") == true)
            label3.Text = disc + "的折扣";
        else
            label3.Text = disc + "的抵购";
        label4.Text = "开始于" + d_start.ToString() +"<br />"+ "  结束于" + d_end.ToString();
        if (d_vip == 1)
            label5.Text = "vip用户才能享受；";
        else
            label5.Text = "面向所有用户";
        d_rules = d_rules.Replace(" ", "&nbsp");
        d_rules = d_rules.Replace("\n", "<br />");
        label6.Text = d_rules;

        img1.ImageUrl = d_image;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string sn_tmp = ind_id + dis_id;
        string sn_code=DESencode(sn_tmp);
        DateTime now = DateTime.Now;
        string start_now = now.Year + "-" + now.Month + "-" + now.Day + " " + now.Hour + ":" + now.Minute + ":" + now.Second;
        SqlConnection sc1 = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
        sc1.Open();

        SqlCommand get_cred = new SqlCommand();
        get_cred.Connection = sc1;
        get_cred.CommandText = "select IND_CREDITS from INFO_IND where IND_ID=@id";
        get_cred.Parameters.AddWithValue("@id",ind_id);
        int crr = Convert.ToInt32(get_cred.ExecuteScalar());
        if (crr >= cred)
        {//插入DISCOUNT_ATTEND表,先验证用户是否已参与过
            SqlCommand get_stat = new SqlCommand("select STATUS from DISCOUNT_ATTEND where DISCOUNT_ID=@did1 and IND_ID=@iid1", sc1);
            get_stat.Parameters.AddWithValue("@did1",dis_id);
            get_stat.Parameters.AddWithValue("@iid1",ind_id);
            object a = get_stat.ExecuteScalar();
            if (a == null)
            {//判断是否是VIP专属，判断用户是否是VIP
                SqlCommand get_vip1 = new SqlCommand("select VIP from INFO_DISCOUNT where DISCOUNT_ID=@did",sc1);
                get_vip1.Parameters.AddWithValue("@did",dis_id);
                int vip1 = Convert.ToInt32(get_vip1.ExecuteScalar().ToString());
                SqlCommand get_vip2 = new SqlCommand("select VIP from IND_CARE where IND_ID=@iid2 and ENTER_ID=(select ENTER_ID from INFO_DISCOUNT where DISCOUNT_ID=@did2)",sc1);
                get_vip2.Parameters.AddWithValue("@iid2",ind_id);
                get_vip2.Parameters.AddWithValue("@did2",dis_id);
                int vip2 = Convert.ToInt32(get_vip2.ExecuteScalar().ToString());
                if ((vip1 == 1 && vip2 == 1) || (vip1 == 0 && vip2 == 0) || (vip1 == 0 && vip2 == 1))
                {
                    SqlCommand update_cred = new SqlCommand("update INFO_IND set IND_CREDITS=IND_CREDITS-@cr where IND_ID=@idd", sc1);
                    update_cred.Parameters.AddWithValue("@cr", cred);
                    update_cred.Parameters.AddWithValue("@idd", ind_id);
                     while (Application["sqllock"] == "lock") 
                     {//检测是否已经锁住               
                         System.Threading.Thread.Sleep(2000);          
                     }
                    Application["sqllock"] = "lock";//上锁 
                    try
                    {
                        update_cred.ExecuteNonQuery();
                    }
                    finally
                    {
                        Application["sqllock"] = "unlock";//解锁 
                    }

                    SqlCommand insert_att = new SqlCommand("insert into DISCOUNT_ATTEND values (@did,@iid,@adate,@sn,@stat)", sc1);
                    insert_att.Parameters.AddWithValue("@did", dis_id);
                    insert_att.Parameters.AddWithValue("@iid", ind_id);
                    insert_att.Parameters.AddWithValue("@adate", start_now);
                    insert_att.Parameters.AddWithValue("@sn", sn_code);
                    insert_att.Parameters.AddWithValue("@stat", 0);
                    while (Application["sqllock"] == "lock")
                    {//检测是否已经锁住               
                        System.Threading.Thread.Sleep(2000);
                    }
                    Application["sqllock"] = "lock";//上锁 

                    if (insert_att.ExecuteNonQuery() == 1)
                    {
                        Application["sqllock"] = "unlock";//解锁
                        sc1.Close();
                        Page.RegisterStartupScript("ss", "<script>alert('参与成功,您的SN码为" + sn_code + "请在会员特权中选择我的优惠查看！')</script>");
                        return;
                    }
                    else
                    {

                        Application["sqllock"] = "unlock";//解锁 
                    }
                }
                else
                {
                    sc1.Close();
                    Page.RegisterStartupScript("ss", "<script>alert('此活动为会员独享优惠！')</script>");
                    return;
                }
            }
            else
            {
                sc1.Close();
                Page.RegisterStartupScript("ss", "<script>alert('您已经参与过啦，每个用户每次优惠只限一次机会哦！')</script>");
                return;
            }
        }
        else
        {
            sc1.Close();
            Page.RegisterStartupScript("ss", "<script>alert('您的积分数不够！')</script>");
            return;
        }

    }
}